package 剑指offer_leetcode;

import java.util.*;

/**
 * JZ77按之字形顺序打印二叉树
 */
public class 剑指Offer32_III_从上到下打印二叉树3 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(root==null)
            return res;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int time = 0;
        while(!q.isEmpty()){
            int n = q.size();
            List<Integer> alist = new ArrayList<Integer>();
            while(n-->0){
                TreeNode node = q.poll();
                alist.add(node.val);
                if(node.left!=null)
                    q.offer(node.left);
                if(node.right!=null)
                    q.offer(node.right);
            }
            time++;
            if(time%2==0)
                Collections.reverse(alist);
            res.add(alist);
        }
        return res;
    }
}
